package com.shanshi.activity;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.shanshi.activity.addressSelector.activity.BaseActivity;
import com.shanshi.activity.addressSelector.adapters.ArrayWheelAdapter;
import com.shanshi.activity.addressSelector.widget.OnWheelChangedListener;
import com.shanshi.activity.addressSelector.widget.WheelView;
import com.shanshi.activity.response.TestTest;
import com.shanshi.activity.service.CompletePersonalInfoService;
import com.shanshi.activity.tool.CustomDialog;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Calendar;
import java.util.List;

public class CompletePersonalInfoActivity extends BaseActivity implements OnClickListener, OnWheelChangedListener,TextWatcher {

	private SharedPreferences sharedPreferences;
	private int lastActivity;//判断是由哪一个页面跳转而来
	private int userId;//用户id
	private TextView tv;
	private ImageView Iv;
	private Button sureBt;
	private ImageView choiceAdd;
	private EditText name;
	private TextView sex;
	private TextView birthday;
	private EditText familyNum;
	private EditText detailAddr;
	
	/****地址弹窗中的view******/
	private WheelView mViewProvince;
	private WheelView mViewCity;
	private WheelView mViewDistrict;
	private TextView tvCancel;
	private TextView tvSure;
	private TextView familyAddr;
	private RelativeLayout testPop;
	
	/*********获取用户定位************/
	private String provider;//位置提供器
    private LocationManager locationManager;//位置服务
    private Location location;
    
    /***********时间选择器用到的变量*************/
    private int mYear;
    private int mMonth;
    private int mDay;
    final int DATE_DIALOG = 1;
	
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.complete_personal_information);

		lastActivity = getIntent().getIntExtra("lastActivity",2);

		init();
		initAddrPopWindow();

		//由推广消息页面跳转而来
		if(lastActivity==1){
			locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);//获得位置服务
			provider = judgeProvider(locationManager);

			if (provider != null) {//有位置提供器的情况

				location = locationManager.getLastKnownLocation(provider);
				if (location != null) {
					getLocation(location);//得到当前经纬度并开启线程去反向地理编码
				} else {
//                tv_show.setText("暂时无法获得当前位置");
				}
			}else{//不存在位置提供器的情况

			}

			/********给时间弹窗赋初值**********/
			final Calendar ca = Calendar.getInstance();
			mYear = ca.get(Calendar.YEAR);
			mMonth = ca.get(Calendar.MONTH);
			mDay = ca.get(Calendar.DAY_OF_MONTH);

		}else if(lastActivity==2){
			//由我的页面跳转而来
			name.setText(sharedPreferences.getString("nickName",""));
			sex.setText(sharedPreferences.getString("sex",""));
			birthday.setText(sharedPreferences.getString("birthday",""));
			familyNum.setText(sharedPreferences.getString("family",""));
			familyAddr.setText(sharedPreferences.getString("addrProv","")+sharedPreferences.getString("addrCity","")+sharedPreferences.getString("addrDis",""));
			detailAddr.setText(sharedPreferences.getString("addrStree",""));
		}

        
	}
	
	
	/*****初始化数据*****/
	@SuppressLint("ResourceAsColor")
	public void init(){
		sharedPreferences = CompletePersonalInfoActivity.this.getSharedPreferences("share", MODE_PRIVATE);
		userId = sharedPreferences.getInt("userId",7);
		Iv = (ImageView) findViewById(R.id.fanhui);
		Iv.setOnClickListener(this);
		sureBt = (Button) findViewById(R.id.sure);
		sureBt.setOnClickListener(this);
		tv = (TextView) findViewById(R.id.title);
		tv.setText("完善个人信息");
		familyAddr = (TextView) findViewById(R.id.familyAddr);
		familyAddr.setOnClickListener(this);
		tvCancel = (TextView) findViewById(R.id.addSelectorCancel);
		tvCancel.setOnClickListener(this);
		tvSure = (TextView) findViewById(R.id.addSelectorSure);
		tvSure.setOnClickListener(this);
		choiceAdd = (ImageView) findViewById(R.id.address);
		choiceAdd.setOnClickListener(this);
		name = (EditText) findViewById(R.id.name);
		sex = (TextView) findViewById(R.id.sex);
		sex.setOnClickListener(this);
		birthday = (TextView) findViewById(R.id.birthday);
		birthday.setOnClickListener(this);
		familyNum = (EditText) findViewById(R.id.familyNum);
		detailAddr = (EditText) findViewById(R.id.detailAddr);

		/************当内容没有填写完毕时不能点击确定按钮**************/
		name.addTextChangedListener(this);
		sex.addTextChangedListener(this);
		birthday.addTextChangedListener(this);
		familyNum.addTextChangedListener(this);
		familyAddr.addTextChangedListener(this);
		detailAddr.addTextChangedListener(this);
	}
	
	
	@Override
	public void onClick(View v) {
		
		switch(v.getId()){
		
		 case R.id.fanhui:
			 finish();
			break;
			
		 case R.id.sure:
			Intent intent = new Intent(this,CompletePersonalInfoService.class);
			intent.putExtra("name", name.getText().toString());
			intent.putExtra("sex", sex.getText().toString());
			intent.putExtra("birthday", birthday.getText().toString());
			intent.putExtra("familyNum", familyNum.getText().toString());
//			intent.putExtra("familyAddr", familyAddr.getText().toString());
			intent.putExtra("mCurrentProviceName", mCurrentProviceName);
			intent.putExtra("mCurrentCityName", mCurrentCityName);
			intent.putExtra("mCurrentDistrictName", mCurrentDistrictName);
			intent.putExtra("detailAddr", detailAddr.getText().toString());
			 intent.putExtra("userId", userId);
			startService(intent);
			
			//动态注册receiver    
			IntentFilter filter = new IntentFilter("CompletePersonalInfoService");    
			filter.addCategory(Intent.CATEGORY_DEFAULT);    
			MessageReceiver receiver = new MessageReceiver();    
			registerReceiver(receiver, filter);
			
			 break;
		 case R.id.birthday:
			 showDialog(DATE_DIALOG);
			 break;
			 
		 case R.id.sex:
			 showSexDialog();
			 break;
			 
		 case R.id.familyAddr:
//			 showAddrPopWindow();
			 setEditTextCannotEdit();
			 testPop = (RelativeLayout) findViewById(R.id.personalInfoPop);
			 testPop.setVisibility(View.VISIBLE);
			 break;
			 
		 case R.id.address:
//			 showAddrPopWindow();
			 setEditTextCannotEdit();
			 testPop = (RelativeLayout) findViewById(R.id.personalInfoPop);
			 testPop.setVisibility(View.VISIBLE);
			 break;
			 
		 case R.id.addSelectorCancel:
			 setEditTextCanEdit();
			 testPop.setVisibility(View.INVISIBLE);
			 break;
			 
		 case R.id.addSelectorSure:
			 setEditTextCanEdit();
			 testPop.setVisibility(View.INVISIBLE);
			 familyAddr.setText(mCurrentProviceName+mCurrentCityName+mCurrentDistrictName);
			 break;
		}
		
		
	}
	
	
	/******设置输入框可以编辑******/
	public void setEditTextCanEdit(){
		name.setFocusable(true);
		name.setFocusableInTouchMode(true);
		sex.setFocusable(true);
		sex.setFocusableInTouchMode(true);
		birthday.setFocusable(true);
		birthday.setFocusableInTouchMode(true);
		familyNum.setFocusable(true);
		familyNum.setFocusableInTouchMode(true);
		detailAddr.setFocusable(true);
		detailAddr.setFocusableInTouchMode(true);
	}
	
	/******设置输入框不可以编辑******/
	public void setEditTextCannotEdit(){
		name.setFocusable(false);
		sex.setFocusable(false);
		birthday.setFocusable(false);
		familyNum.setFocusable(false);
		detailAddr.setFocusable(false);
	}
	
	
	/*****自定义选择地址的弹窗*******/
	/*public void showAddrPopWindow() {  
		  
	    final AlertDialog mDialog = new AlertDialog.Builder(this).create();  
	    mDialog.show();  
	    Window window = mDialog.getWindow();  
	    window.setGravity(Gravity.BOTTOM);  
	    window.setWindowAnimations(R.style.popupAnimation);  
	    View view = View.inflate(this, R.layout.address_selector, null); 
	    initAddrPopWindow();
	    tvCancel = (TextView) findViewById(R.id.addSelectorCancel);
		tvSure = (TextView) findViewById(R.id.addSelectorSure);
		tvCancel.setOnClickListener(new View.OnClickListener() {  
	        @Override  
	        public void onClick(View v) {  
	        	mDialog.dismiss();
	        }  
	    });  
		tvSure.setOnClickListener(new View.OnClickListener() {  
	        @Override  
	        public void onClick(View v) {  
	        	familyAddr = (TextView) findViewById(R.id.familyAddr);
	        	familyAddr.setText(mCurrentProviceName+mCurrentCityName+mCurrentDistrictName);
	        	mDialog.dismiss();
	        }  
	    });
	    window.setContentView(view);  
	    window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);//设置横向全屏  
	  
	    mDialog.setCanceledOnTouchOutside(false);  
	    mDialog.setCancelable(true);
	}*/
	
	
	/******初始化地址弹窗中的数据*********/
	public void initAddrPopWindow() {
		setUpViews();
		setUpListener();
		setUpData();
	}
	
	private void setUpViews() {
		mViewProvince = (WheelView) findViewById(R.id.id_province);
		mViewCity = (WheelView) findViewById(R.id.id_city);
		mViewDistrict = (WheelView) findViewById(R.id.id_district);
	}
	
	private void setUpListener() {
    	// 添加change事件
    	mViewProvince.addChangingListener(this);
    	// 添加change事件
    	mViewCity.addChangingListener(this);
    	// 添加change事件
    	mViewDistrict.addChangingListener(this);
    }
	
	private void setUpData() {
		initProvinceDatas();
		mViewProvince.setViewAdapter(new ArrayWheelAdapter<String>(CompletePersonalInfoActivity.this, mProvinceDatas));
		// 设置可见条目数量
		mViewProvince.setVisibleItems(7);
		mViewCity.setVisibleItems(7);
		mViewDistrict.setVisibleItems(7);
		updateCities();
		updateAreas();
	}

	@Override
	public void onChanged(WheelView wheel, int oldValue, int newValue) {
		// TODO Auto-generated method stub
		if (wheel == mViewProvince) {
			updateCities();
		} else if (wheel == mViewCity) {
			updateAreas();
		} else if (wheel == mViewDistrict) {
			mCurrentDistrictName = mDistrictDatasMap.get(mCurrentCityName)[newValue];
			mCurrentZipCode = mZipcodeDatasMap.get(mCurrentDistrictName);
		}
	}

	/**
	 * 根据当前的市，更新区WheelView的信息
	 */
	private void updateAreas() {
		int pCurrent = mViewCity.getCurrentItem();
		mCurrentCityName = mCitisDatasMap.get(mCurrentProviceName)[pCurrent];
		String[] areas = mDistrictDatasMap.get(mCurrentCityName);

		if (areas == null) {
			areas = new String[] { "" };
		}
		mViewDistrict.setViewAdapter(new ArrayWheelAdapter<String>(this, areas));
		mViewDistrict.setCurrentItem(0);
	}

	/**
	 * 根据当前的省，更新市WheelView的信息
	 */
	private void updateCities() {
		int pCurrent = mViewProvince.getCurrentItem();
		mCurrentProviceName = mProvinceDatas[pCurrent];
		String[] cities = mCitisDatasMap.get(mCurrentProviceName);
		if (cities == null) {
			cities = new String[] { "" };
		}
		mViewCity.setViewAdapter(new ArrayWheelAdapter<String>(this, cities));
		mViewCity.setCurrentItem(0);
		updateAreas();
	}



	// 接收广播类
		public class MessageReceiver extends BroadcastReceiver {
			@Override
			public void onReceive(Context context, Intent intent) {
				String message = intent.getStringExtra("result");
				Gson gson=new Gson();
				TestTest content=gson.fromJson(message,TestTest.class);
				if(content.getCode()==10001){
					//存储全局变量
					SharedPreferences.Editor editor = sharedPreferences.edit();
					editor.putString("nickName",name.getText().toString());
					editor.putString("sex",sex.getText().toString());
					editor.putString("birthday",birthday.getText().toString());
					editor.putString("family",familyNum.getText().toString());
					editor.putString("addrProv",mCurrentProviceName);
					editor.putString("addrCity",mCurrentCityName);
					editor.putString("addrDis",mCurrentDistrictName);
					editor.putString("addrStree",detailAddr.getText().toString());
					editor.commit();
					//跳转至下一个页面
					Intent nextIntent = null;
					if(lastActivity==1){
						nextIntent = new Intent(CompletePersonalInfoActivity.this, paymentActivity.class);
					}else if(lastActivity==2){
						nextIntent = new Intent(CompletePersonalInfoActivity.this, SpreadMessage.class);
					}
					startActivity(nextIntent);
				}else{
					//请求url或参数错误
					Toast.makeText(CompletePersonalInfoActivity.this, "完善个人资料失败", Toast.LENGTH_SHORT).show();
				}
				context.unregisterReceiver(this);

			}
		}
		
		/************创建时间弹窗***************/
		@Override
	    protected Dialog onCreateDialog(int id) {
	        switch (id) {
	            case DATE_DIALOG:
	                return new DatePickerDialog(this, mdateListener, mYear, mMonth, mDay);
	        }
	        return null;
	    }

		/**
	     * 设置日期 利用StringBuffer追加
	     */
	    public void display() {
			String month = (mMonth+1)+"";
			String day = mDay+"";
			if(mMonth+1<10){
				month = "0"+month;
			}
			if(mDay<10){
				day = "0"+day;
			}
	    	birthday.setText(new StringBuffer().append(mYear).append("-").append(month).append("-").append(day));
	    }

	    private DatePickerDialog.OnDateSetListener mdateListener = new DatePickerDialog.OnDateSetListener() {

	        @Override
	        public void onDateSet(DatePicker view, int year, int monthOfYear,
	                              int dayOfMonth) {
	            mYear = year;
	            mMonth = monthOfYear;
	            mDay = dayOfMonth;
	            display();
	        }
	    };
	    
		/***********展示性别选择弹窗************/
	    public void showSexDialog(){
			CustomDialog.Builder builder = new CustomDialog.Builder(this);
	        builder.setTitle("请选择性别：");  
	        builder.setPositiveButton("女", new DialogInterface.OnClickListener() {  
	            public void onClick(DialogInterface dialog, int which) {  
	                dialog.dismiss();  
	                sex.setText("女");
//	                //设置你的操作事项  
	            }  
	        });  
	  
	        builder.setNegativeButton("男",  
	                new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int which) {  
	                        dialog.dismiss();  
	                        sex.setText("男");
	                    }  
	                });  
	  
	        CustomDialog customDialog = builder.create(R.layout.complete_personnal_info_sexpopwindow,R.id.sex_title,R.id.sex_man,R.id.sex_woman,0,0);
	        customDialog.show();
	        
	        //设置弹窗之外的部分不能点击
	        customDialog.setCanceledOnTouchOutside(false);
		}
	    
	    
		/************
		 * tool
		 * time :2017-3-10
		 * author :scx
		 * 获取定位根据百度地图反编译得到用户地址
		 * 
		 * ****************/
		
		    /**
		     * 得到当前经纬度并开启线程去反向地理编码
		     */
		    public void getLocation(Location location) {
		        String latitude = location.getLatitude()+"";
		        String longitude = location.getLongitude()+"";
		        String url = "http://api.map.baidu.com/geocoder/v2/?ak=pPGNKs75nVZPloDFuppTLFO3WXebPgXg&callback=renderReverse&location="+latitude+","+longitude+"&output=json&pois=0";
		        new MyAsyncTask(url).execute();
		    }

		    /**
		     * 判断是否有可用的内容提供器
		     * @return 不存在返回null
		     */
		    private String judgeProvider(LocationManager locationManager) {
		        List<String> prodiverlist = locationManager.getProviders(true);
		        if(prodiverlist.contains(LocationManager.NETWORK_PROVIDER)){
		            return LocationManager.NETWORK_PROVIDER;
		        }else if(prodiverlist.contains(LocationManager.GPS_PROVIDER)) {
		            return LocationManager.GPS_PROVIDER;
		        }else{
		            Toast.makeText(CompletePersonalInfoActivity.this,"没有可用的位置提供器",Toast.LENGTH_SHORT).show();
		        }
		        return null;
		    }

		    class MyAsyncTask extends AsyncTask<Void,Void,Void>{
		        String url = null;//要请求的网址
		        String str = null;//服务器返回的数据
		        String address = null;
		        public MyAsyncTask(String url){
		            this.url = url;
		        }
		        @Override
		        protected Void doInBackground(Void... params) {
//		            str = GetHttpConnectionData.getData(url);
		            Request request = new Request.Builder()
		                    .url(url)
		                    .build();
		            str =   execute(request);
		            return null;
		        }
		        @Override
		        protected void onPostExecute(Void aVoid) {
		            try {
		                str = str.replace("renderReverse&&renderReverse","");
		                str = str.replace("(","");
		                str = str.replace(")","");
		                JSONObject jsonObject = new JSONObject(str);
		                JSONObject address = jsonObject.getJSONObject("result");
		                JSONObject str2 = address.getJSONObject("addressComponent");
		                String province = str2.getString("province");
		                String city = str2.getString("city");
		                String district = str2.getString("district");
		                familyAddr.setText(province+city+district);
						//更新全局变量
						mCurrentProviceName = province;
						mCurrentCityName = city;
						mCurrentDistrictName = district;
		            } catch (JSONException e) {
		                e.printStackTrace();
		            }
		            super.onPostExecute(aVoid);
		        }
		        public String execute(Request request){
		            try {
		                OkHttpClient client = new OkHttpClient();
		                Response response = client.newCall(request).execute();
		               if (response.isSuccessful()) {
		                   return response.body().string();
		               } 
		           } catch (IOException e) {
		               e.printStackTrace();
		           }
		           return "error";
		        }
		    }

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after) {

	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {

	}

	@Override
	public void afterTextChanged(Editable s) {
		if(TextUtils.isEmpty(name.getText().toString())||TextUtils.isEmpty(sex.getText().toString())||TextUtils.isEmpty(birthday.getText().toString())||
				TextUtils.isEmpty(familyNum.getText().toString())||TextUtils.isEmpty(familyAddr.getText().toString())
				||TextUtils.isEmpty(detailAddr.getText().toString())){
			sureBt.setEnabled(false);
			sureBt.setBackgroundResource(R.drawable.button_style3);
		}else{
			sureBt.setEnabled(true);
			sureBt.setBackgroundResource(R.drawable.button_style);
		}
	}
}
